﻿using AutoMapper;
using B.S.BaseData.Api.Read.Command.GoodsCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.DTO.GoodsDTO;
using B.S.BataBase.Domain.Entitys;
using MediatR;

namespace B.S.BaseData.Api.Read.CommandHandler.GoodsCommandHandler
{
    public class GoodsdetailCommandHandler : IRequestHandler<GoodsdetailCommand, APIResult<GoodInfoDTO>>
    {
        private readonly IBaseRepository<GoodsInfo> _goodsinforepository;
        private readonly IBaseRepository<GoodsType> _goodsTyperepository;
        private readonly IMapper _mapper;
        public GoodsdetailCommandHandler(IBaseRepository<GoodsInfo> goodsinforepository, IBaseRepository<GoodsType> goodsTyperepository, IMapper mapper)
        {
            _goodsinforepository = goodsinforepository;
            _goodsTyperepository = goodsTyperepository;
            _mapper = mapper;
        }

        public async Task<APIResult<GoodInfoDTO>> Handle(GoodsdetailCommand request, CancellationToken cancellationToken)
        {
            APIResult<GoodInfoDTO> result=new APIResult<GoodInfoDTO>();
            try
            {
                var list = await _goodsinforepository.GetValues(x => x.Id == request.Id);
                var res = _mapper.Map<GoodInfoDTO>(list);
                res.GoodsTypeName = (await _goodsTyperepository.GetValues(x => x.Id == list.GoodsName)).GoodTypeName;
                result.Code = ApiEnum.Success;
                result.Msg = "商品详情显示成功";
                result.Data= res;
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Success;
                result.Msg = $"商品详情显示异常，异常为：{ex.Message}";
                return await Task.FromResult(result);
            }
        }
    }
}
